package com.shxzz.easy12306.framework.starter.designpattern.chain;

import com.shxzz.easy12306.framework.starter.base.ApplicationContextHolder;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.Ordered;

import java.util.*;

/**
 * 责任链上下文容器
 * @author shxzz
 * @create 2024-02-20-18:52
 */
public class AbstractChainContext implements CommandLineRunner {
    private final Map<String, List<AbstractChainHandler>> chainHandlerContext = new HashMap<>();

    /**
     * 根据标识调用责任链执行
     */
    public void handler(String mark, Object requestParam) {
        List<AbstractChainHandler> chainHandlerList = chainHandlerContext.get(mark);

        if (chainHandlerList == null) {
            return;
        }

        chainHandlerList.forEach(item -> {
            item.handler(requestParam);
        });
    }

    @Override
    public void run(String... args) throws Exception {
        Map<String, AbstractChainHandler> chainHandlerMap = ApplicationContextHolder.getBeansOfType(AbstractChainHandler.class);

        chainHandlerMap.values().forEach(item -> {
            List<AbstractChainHandler> chainHandlerList = chainHandlerContext.getOrDefault(item.mark(), null);
            if (chainHandlerList == null) {
                chainHandlerList = new ArrayList<>();
                chainHandlerContext.put(item.mark(), chainHandlerList);
            }
            chainHandlerList.add(item);
        });

        chainHandlerContext.values().forEach(item -> item.sort(Comparator.comparingInt(Ordered::getOrder)));
    }
}
